{% extends "base.html" %}

{% block title %}Meats - PinCaiCai 2.0{% endblock %}

{% block content %}
<div class="container mt-4">
    <h2>Meat Products</h2>
    
    <!-- Sort and filter controls -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="input-group">
                <span class="input-group-text">Sort By</span>
                <select class="form-select" id="sortSelect" onchange="sortProducts()">
                    <option value="name_asc">Name A-Z</option>
                    <option value="name_desc">Name Z-A</option>
                    <option value="price_asc">Price Low-High</option>
                    <option value="price_desc">Price High-Low</option>
                    <option value="stock_desc">Stock High-Low</option>
                </select>
            </div>
        </div>
        <div class="col-md-6">
            <div class="input-group">
                <span class="input-group-text">Search</span>
                <input type="text" class="form-control" id="searchInput" placeholder="Search product names..." onkeyup="filterProducts()">
            </div>
        </div>
    </div>
    
    <div class="row" id="products-container">
        <!-- Products will be dynamically loaded via JavaScript -->
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let allProducts = [];
let filteredProducts = [];

document.addEventListener('DOMContentLoaded', function() {
    loadProducts('meats');
});

function loadProducts(category) {
    fetch(`/api/products?category=${encodeURIComponent(category)}`)
        .then(response => response.json())
        .then(data => {
            allProducts = data.products || [];
            filteredProducts = [...allProducts];
            displayProducts();
        })
        .catch(error => {
            console.error('Error loading products:', error);
            document.getElementById('products-container').innerHTML = '<div class="col-12 text-center"><p>Failed to load products</p></div>';
        });
}

function displayProducts() {
    const container = document.getElementById('products-container');
    if (filteredProducts.length > 0) {
        container.innerHTML = '';
        filteredProducts.forEach(product => {
            const col = document.createElement('div');
            col.className = 'col-md-3 mb-4';
            col.innerHTML = `
                <div class="card product-card h-100">
                    <div class="card-img-top d-flex align-items-center justify-content-center" style="height: 150px; background-color: #f8f9fa; font-size: 3rem;">
                        ${product.emoji || '📦'}
                    </div>
                    <div class="card-body d-flex flex-column">
                        <h5 class="card-title">${product.name}</h5>
                        <p class="card-text">${product.description || ''}</p>
                        <p class="text-success fw-bold">¥${product.price}</p>
                        <p class="text-muted">Stock: ${product.stock}</p>
                        
                        <!-- Quantity selector -->
                        <div class="mb-3">
                            <label class="form-label">Quantity:</label>
                            <div class="input-group">
                                <button class="btn btn-outline-secondary" type="button" onclick="changeQuantityMeats(${product.product_id}, -1)">-</button>
                                <input type="number" class="form-control text-center" id="quantity-${product.product_id}" value="1" min="1" max="${product.stock}">
                                <button class="btn btn-outline-secondary" type="button" onclick="changeQuantityMeats(${product.product_id}, 1)">+</button>
                            </div>
                        </div>
                        
                        <!-- Action buttons -->
                        <div class="mt-auto">
                            <button class="btn btn-primary w-100 mb-2" onclick="addToCart(${product.product_id})">Add to Cart</button>
                            <button class="btn btn-success w-100" onclick="buyNow(${product.product_id})">Buy Now</button>
                        </div>
                    </div>
                </div>
            `;
            container.appendChild(col);
        });
    } else {
        container.innerHTML = '<div class="col-12 text-center"><p>No products available</p></div>';
    }
}

function changeQuantityMeats(productId, change) {
    const input = document.getElementById(`quantity-${productId}`);
    const currentValue = parseInt(input.value);
    const newValue = Math.max(1, Math.min(currentValue + change, parseInt(input.max)));
    input.value = newValue;
}

function sortProducts() {
    const sortBy = document.getElementById('sortSelect').value;
    
    filteredProducts.sort((a, b) => {
        switch(sortBy) {
            case 'name_asc':
                return a.name.localeCompare(b.name);
            case 'name_desc':
                return b.name.localeCompare(a.name);
            case 'price_asc':
                return a.price - b.price;
            case 'price_desc':
                return b.price - a.price;
            case 'stock_desc':
                return b.stock - a.stock;
            default:
                return 0;
        }
    });
    
    displayProducts();
}

function filterProducts() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    filteredProducts = allProducts.filter(product => 
        product.name.toLowerCase().includes(searchTerm)
    );
    displayProducts();
}

function addToCart(productId) {
    const quantity = parseInt(document.getElementById(`quantity-${productId}`).value);
    
    fetch('/api/cart/add', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            category: 'meats',
            product_id: productId,
            quantity: quantity
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(`Added ${quantity} items to cart!`);
        } else if (data.error && data.error.includes('login')) {
            alert('Please login first before adding to cart!');
            // Can add logic to redirect to login page here
        } else {
            alert('Add to cart failed: ' + (data.error || data.message || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error adding to cart:', error);
        alert('Add to cart failed, please try again');
    });
}

function buyNow(productId) {
    const quantity = parseInt(document.getElementById(`quantity-${productId}`).value);
    
    if (confirm(`Are you sure you want to buy ${quantity} items?`)) {
        // Create order directly
        fetch('/api/orders', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                items: [{
                    category: 'meats',
                    product_id: productId,
                    quantity: quantity
                }]
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.message && data.message.includes('success')) {
                alert('Order created successfully!');
                window.location.href = '/orders';
            } else if (data.error && data.error.includes('login')) {
                alert('Please login first before purchasing!');
            } else {
                alert('Purchase failed: ' + (data.error || data.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error buying now:', error);
            alert('Purchase failed, please try again');
        });
    }
}
</script>
{% endblock %}
